package com.cwits.wifi.ui.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cwits.wifi.R;
import com.cwits.wifi.base.BaseActivity;
import com.cwits.wifi.util.PreferencesHelper;

import java.util.List;
import java.util.Random;

/**
 * Created by ZhangHua on 2016/5/21.
 */
public class PengCiActivity extends BaseActivity implements View.OnClickListener{

    private RelativeLayout mBack;
    private WebView mWebView;
    private TextView titile_back;
    private boolean mIsNeedReConnect = true;
    private ProgressDialog progressDialog;
    private boolean mLoad = true;

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION))
            {
                ConnectivityManager mConnectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
                if(netInfo != null && netInfo.isAvailable()) {

                    /////////////网络连接
                    mWebView.reload();
                } else {
                    ////////网络断开

                }
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pengcilayout);
        mBack = (RelativeLayout) findViewById(R.id.left_imageview);
        titile_back = (TextView) findViewById(R.id.titile_back);
        String title = getString(R.string.pengci_titile);
        titile_back.setText(title);
        mWebView = (WebView) findViewById(R.id.webView);
        if(mApplication.getIsOffLineMode() == false)
        {
            disconnectDevice();
            mApplication.setIsOffLineMode(true);
            mApplication.setRealCamera(false);
            mApplication.setIsNeedReconnect(true);
        }
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setAppCacheEnabled(false);
        mWebView.setVisibility(View.INVISIBLE);
        String tid = PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString("device_id", "xxx");
        if(tid.equals("xxx"))
            tid = "";
        mWebView.loadUrl("http://cross.kcnzq.net:8099/app/bx/new/index.html?tid="
                + tid + "&random=" + new Random().nextInt(99999999) + "&showtitle");
        mWebView.setWebViewClient(mWebViewClient);
        mWebView.addJavascriptInterface(this,"submit");
        mWebView.setWebChromeClient(new WebChromeClient() {

                                       @Override
                                        public void onProgressChanged(WebView view, int progress) {
                                           // TODO Auto-generated method stub
                                           super.onProgressChanged(view, progress);

                                        }

                                        @Override
                                        public boolean onJsAlert(WebView view, String url, String message,
                                                                 JsResult result) {
                                            // TODO Auto-generated method stub
                                            return super.onJsAlert(view, url, message, result);
                                        }

                                       @Override
                                       public boolean onJsConfirm(WebView view, String url, String message,
                                                                  JsResult result) {
                                           // TODO Auto-generated method stub
                                           return super.onJsConfirm(view, url, message, result);
                                       }

                                       @Override
                                       public boolean onJsPrompt(WebView view, String url, String message,
                                                                 String defaultValue, JsPromptResult result) {
                                           // TODO Auto-generated method stub
                                           return super.onJsPrompt(view, url, message, defaultValue,result);
                                       }
                                    }
        );
        mBack.setOnClickListener(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, filter);

        //lihaoran: clear PushMSM count
        //clearPushMSMCount();
    }

    @Override
    public void onClick(View v) {
        switch(v.getId())
        {
            case R.id.left_imageview:
                if(mWebView.canGoBack())
                {
                    mWebView.goBack();
                }else
                {
                    finish();
                }

                break;
        }
    }

    @Override
    public void onBackPressed() {
        if(mWebView.canGoBack())
        {
            mWebView.goBack();
        }else
        {
            finish();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(mReceiver);
    }

    private void clearPushMSMCount() {
        int msmCount = PreferencesHelper.getSharedPreferences(this).getInt("PushMSMCount", 0);
        if(msmCount!=0) {
            PreferencesHelper.putIntValue(this, "PushMSMCount", 0);
        }
    }

    @JavascriptInterface
    public void clickOnAndroid() {

        if(isWeixinAvilible(this)){

            // 获取剪贴板管理器：
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", "zhongbaoclub");
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);

            //showToastLong("安装微信");
            Intent intent = new Intent();
            ComponentName cmp = new ComponentName("com.tencent.mm",
                    "com.tencent.mm.ui.LauncherUI");// 报名该有activity

            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(cmp);

            startActivityForResult(intent, 0);
        }else{
            showToastLong("没有安装微信");
        }

    }

    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }


    private final WebViewClient mWebViewClient = new WebViewClient(){

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, android.net.http.SslError error) {
            handler.proceed();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            // TODO Auto-generated method stub
            super.onReceivedError(view, errorCode, description, failingUrl);
            mWebView.setVisibility(View.INVISIBLE);
            mLoad = false;
        }

        //在页面加载开始时调用。
        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);
            if(progressDialog != null&&progressDialog.isShowing()){
                progressDialog.dismiss();
            }
            if(mLoad)
                mWebView.setVisibility(View.VISIBLE);
        }

        //在加载页面资源时会调用，每一个资源（比如图片）的加载都会调用一次。
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
            mLoad = true;
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(PengCiActivity.this);
                progressDialog.setMessage(getString(R.string.data_downloading));
            }
            progressDialog.show();
        }

        //重写此方法才能够处理在浏览器中的按键事件
        @Override
        public void onLoadResource(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onLoadResource(view, url);

        }

        //重写此方法可以让webview处理https请求。
        @Override
        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
            return super.shouldOverrideKeyEvent(view, event);
        }

    };
}
